package com.zbb.online_exam.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbb.online_exam.dto.PaperDto;
import com.zbb.online_exam.dto.TableDto;
import com.zbb.online_exam.entity.*;
import com.zbb.online_exam.mapper.ExamMapper;
import com.zbb.online_exam.mapper.PaperMapper;
import com.zbb.online_exam.mapper.RelationMapper;
import com.zbb.online_exam.service.ExamService;
import com.zbb.online_exam.service.PaperService;
import com.zbb.online_exam.utils.ExamUtils;
import com.zbb.online_exam.vo.AnswerVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zbbstart
 * @date 2021/2/15 - 17:18
 */
@Service
@Slf4j
public class ExamServiceImpl implements ExamService {
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private RelationMapper relationMapper;
    @Autowired
    private PaperService paperService;
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private ExamUtils examUtils;

    @Override
    public TableDto getAllExams(Integer studentNo, Integer pageNo, Integer size) {
        //根据学生编号获取其老师的编号
        Integer teacherNo = relationMapper.selectOne(new QueryWrapper<Relation>().eq("studentNo", studentNo)).getTeacherNo();
        //查询老师创建的未过期的试卷
        QueryWrapper<Paper> wrapper = new QueryWrapper<Paper>()
                .eq("teacherNo", teacherNo)
                //0,未生成，1,已生成未过期,2已过期
                .eq("status", 1);
        //查找老师所有的试卷
        List<Paper> papers = paperMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(papers)) {
            return examUtils.setTableDto();
        }
        List<String> paperNos = new ArrayList<>();
        papers.forEach(p -> paperNos.add(p.getPaperNo()));
        //判断paperNo(examNo)是否都有
        List<Exam> exams = examMapper.selectList(new QueryWrapper<Exam>().eq("studentNo", studentNo));
        List<String> examNos = new ArrayList<>();
        exams.forEach(e -> examNos.add(e.getExamNo()));
        //比较两个集合
        List<String> different = examUtils.getDifferent(paperNos, examNos);
        if (CollectionUtils.isNotEmpty(different)) {
            for (String examNo : different) {
                synchronized (this) {
                    Exam exam = new Exam();
                    exam.setExamNo(examNo);
                    exam.setExamScore("--");
                    exam.setStudentNo(studentNo);
                    exam.setExamStatus("0");
                    examMapper.insert(exam);
                }
            }
        }
        //分页
        Page<Exam> page = new Page<>(pageNo, size);
        //当前学生的考试试卷
        QueryWrapper<Exam> queryWrapper = new QueryWrapper<Exam>().eq("studentNo", studentNo);
        Page<Exam> examPage = examMapper.selectPage(page, queryWrapper);

        return examUtils.setTableDto(examPage.getTotal(), examUtils.transformExamList(examPage.getRecords()));
    }

    @Override
    public void getStudentAnswers(AnswerVo answerVo) {
        log.info("试卷提交后获取的信息:" + answerVo);
        //获取学生回答的答案
        List<Option> answers = answerVo.getAnswers();
        //获取当前试卷的答案
        Integer paperId = paperService.getPaperByExamNo(answerVo.getExamNo()).getPaperId();
        Paper paper = paperService.getPaperAllInfo(paperId);
        List<String> corAnswers = paper.getQuestionList().stream().map(QuestionEntity::getCorrectAnswer).collect(Collectors.toList());
        //对比获取总分
        int totalgrade = 0;
        //创建学生答案列表
        for (Option option : answers) {
            synchronized (this) {
                if (corAnswers.get(option.getQuestionNo() - 1).equals(option.getOption())) {
                    totalgrade += paper.getScorePerQuestion();
                }
            }
        }
        String examNo = answerVo.getExamNo();
        log.info("每题分数:" + paper.getScorePerQuestion() + "\t总分:" + totalgrade);
        Integer studentNo = answerVo.getStudentNo();
        log.info("学生编号:" + studentNo);
        //写入数据库，更新exam表，状态为2已考，总分，stu_answers 学生回答列表
        examMapper.update(new Exam(), new UpdateWrapper<Exam>()
                .eq("studentNo", studentNo)
                .eq("examNo", examNo)
                .set("examStatus", 2)
                .set("examScore", String.valueOf(totalgrade))
                .set("studentNo",studentNo)
                .set("stu_answers", answers.toString()));

    }

    @Override
    public PaperDto checkPaper(Integer studentNo, String examNo) {
        //获取当前试卷
        Integer paperId = paperService.getPaperByExamNo(examNo).getPaperId();
        Paper paper = paperService.getPaperAllInfo(paperId);
        //获取当前试卷学生回答的考试信息
        Exam exam = examMapper.selectOne(new QueryWrapper<Exam>()
                .eq("studentNo", studentNo)
                .eq("examNo", examNo));
        PaperDto paperDto = new PaperDto();
        paperDto.setPaper(paper);
        paperDto.setExam(exam);
        return paperDto;
    }
}
